package windelpdv;

import br.com.daruma.jna.DUAL;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Marcio
 */
public class dlgFinalizaCupom extends javax.swing.JDialog {
    
    int Cod_cupom;
    float Subtotal;
    Dimension tela = Toolkit.getDefaultToolkit().getScreenSize();
    boolean cupomEncerrado = false;
    private Connection ConexaoPDVWindel = null;
    DefaultTableModel tabela = new DefaultTableModel(null, new String[]{"Cód", "Produto", "Quant", "Preço", "Total"});
    Vector vetor_itens = new Vector();
    
    public dlgFinalizaCupom(java.awt.Frame parent, boolean modal, float Subtotal, DefaultTableModel Tabela, Connection conexaoPDVWindel, Vector vetor_itens) {
        super(parent, modal);
        this.Subtotal = Subtotal;
        this.tabela = Tabela;
        this.ConexaoPDVWindel = conexaoPDVWindel;
        this.vetor_itens = vetor_itens;
        initComponents();
        setSize(600, 600); //ponha aqui suas medidas  
        setLocation((tela.width - this.getSize().width) / 2, (tela.height - this.getSize().height) / 2);
        tfValorPago.grabFocus();
        tfTotalCupom.setText(formatarFloat(this.Subtotal));      
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        tfTotalCupom = new javax.swing.JTextField();
        tfTotalCupom.setHorizontalAlignment(tfTotalCupom.RIGHT);
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        tfValorPago = new javax.swing.JTextField();
        tfValorPago = new JMoneyField();

        jLabel4 = new javax.swing.JLabel();
        tfTroco = new javax.swing.JTextField();
        tfTroco.setHorizontalAlignment(tfTroco.RIGHT);
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        rbDinheiro = new javax.swing.JRadioButton();
        rbCheque = new javax.swing.JRadioButton();
        rbCrediario = new javax.swing.JRadioButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Finalizar Cupom");

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/windelpdv/imagens/Logo2.jpg"))); // NOI18N

        tfTotalCupom.setEditable(false);
        tfTotalCupom.setFont(new java.awt.Font("Times New Roman", 1, 36)); // NOI18N

        jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 36)); // NOI18N
        jLabel2.setText("Total Cupom");

        jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 36)); // NOI18N
        jLabel3.setText("Valor Pago");

        tfValorPago.setFont(new java.awt.Font("Times New Roman", 1, 36)); // NOI18N
        tfValorPago.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfValorPagoActionPerformed(evt);
            }
        });
        tfValorPago.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfValorPagoKeyPressed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Times New Roman", 1, 36)); // NOI18N
        jLabel4.setText("Troco");

        tfTroco.setEditable(false);
        tfTroco.setFont(new java.awt.Font("Times New Roman", 1, 36)); // NOI18N

        jLabel5.setFont(new java.awt.Font("Bookman Old Style", 2, 18)); // NOI18N
        jLabel5.setText("Obrigado pela preferência. Volte sempre!");

        jLabel6.setText("F12 - Finaliza Cupom");

        jLabel7.setText("Esc - Volta venda");

        jLabel8.setText("F1 - Dinheiro");

        jLabel9.setText("F2 - Cheque");

        jLabel10.setText("F3 - Crediário");

        buttonGroup1.add(rbDinheiro);
        rbDinheiro.setSelected(true);

        buttonGroup1.add(rbCheque);

        buttonGroup1.add(rbCrediario);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 430, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(tfTotalCupom, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(33, 33, 33))
                                    .addComponent(tfValorPago, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(48, 48, 48)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jLabel9)
                                            .addComponent(jLabel10)
                                            .addComponent(jLabel8))
                                        .addGap(18, 18, 18)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(rbDinheiro)
                                            .addComponent(rbCrediario)
                                            .addComponent(rbCheque)))
                                    .addComponent(tfTroco, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(0, 0, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(31, 31, 31)
                        .addComponent(jLabel7)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel6)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(26, 26, 26)
                .addComponent(jLabel5)
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfTotalCupom, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(tfValorPago, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(tfTroco, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(33, 33, 33)
                        .addComponent(jLabel8)
                        .addGap(5, 5, 5))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rbDinheiro)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(rbCheque)
                    .addComponent(jLabel9))
                .addGap(5, 5, 5)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel6)
                        .addComponent(jLabel7)
                        .addComponent(jLabel10))
                    .addComponent(rbCrediario))
                .addGap(31, 31, 31))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tfValorPagoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfValorPagoActionPerformed
    }//GEN-LAST:event_tfValorPagoActionPerformed

    private void tfValorPagoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfValorPagoKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_F10) {
            int iRetorno;
            iRetorno = DUAL.rStatusImpressora();
            JOptionPane.showMessageDialog(null, iRetorno, "Mensagem", JOptionPane.INFORMATION_MESSAGE);
            
        }
        if (evt.getKeyCode() == KeyEvent.VK_F12) {
            cupomEncerrado = true;
            float tr = Float.valueOf(tfValorPago.getText().replace(",", "."));
            float troco = tr - Subtotal;
            tfTroco.setText(formatarFloat(troco));
            int Dinheiro = 0;
            int Cheque = 0;
            int Crediario = 0;
            
            if (rbDinheiro.isSelected()){
                Dinheiro = 1;
            }
            if (rbCheque.isSelected()){
                Cheque = 1;
            }
            if (rbCrediario.isSelected()){
                Crediario = 1;
            }

            Date data = new Date(System.currentTimeMillis());
            SimpleDateFormat formatarDate = new SimpleDateFormat("yyyy-MM-dd");
            
            Statement st = null;
            ResultSet res = null;
            try {
                    
                    st = ConexaoPDVWindel.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                    res = st.executeQuery("SELECT MAX(COD_CUPOM) FROM FECHA_CAIXA");
                    res.first();
                    Cod_cupom = res.getInt("MAX");
                    Cod_cupom = Cod_cupom + 1;
                    
                   st.execute("insert into FECHA_CAIXA (DATA, DINHEIRO, CHEQUE, CREDIARIO, COD_CUPOM, TOTAL_CUPOM) values ("+
                                "\'" + (formatarDate.format(data)) + "\',"+
                                 + Dinheiro + ","+
                                 + Cheque + ","+
                                 + Crediario + ","+
                                 + Cod_cupom + ","+
                                 + Subtotal + ")" );                    
                } catch (SQLException e) {
                    JOptionPane.showMessageDialog(null, "Registros não inseridos!", "Erro", JOptionPane.INFORMATION_MESSAGE);
                }
           
                String tsProdutos = "<dt></dt> <hr></hr><sl>1</sl> <b> <ce> CUPOM NAO FISCAL    COD." + Cod_cupom + "</ce> </b>  <l></l>"
                    + "Item  Descricao             Quant Preco  Total <l></l>";
            
            for (int i = 0; i < tabela.getRowCount(); i++) {
                
                //Arruma item para XX caracteres
                String formItem = tabela.getValueAt(i, 0).toString();
                int tamItem = formItem.length();
                while (tamItem < 3) {
                    formItem = formItem + " ";
                    tamItem = tamItem + 1;
                }
                
                //Arruma descricao para XX caracteres
                String formDescricao = tabela.getValueAt(i, 1).toString();
                int tamDescricao = formDescricao.length();
                while (tamDescricao < 24) {
                    formDescricao = formDescricao + " ";
                    tamDescricao = tamDescricao + 1;
                }
                if (tamDescricao > 24) {
                    formDescricao = formDescricao.substring(0, 24);
                }

                //Arruma quant para XX caracteres
                String formQuant = tabela.getValueAt(i, 2).toString();
                int tamQuant = formQuant.length();
                while (tamQuant < 5) {
                    formQuant = formQuant + " ";
                    tamQuant = tamQuant + 1;
                }
                
                //Arruma linha cupom para XX caracteres
                String txProdutos = (formItem + ""
                        + formDescricao + " "
                        + formQuant + " "
                        + tabela.getValueAt(i, 3).toString() + "   "
                        + tabela.getValueAt(i, 4).toString());
                int tamTxProdutos = txProdutos.length();
                while (tamTxProdutos < 48) {
                    txProdutos = txProdutos + " ";
                    tamTxProdutos = tamTxProdutos + 1;
                }
               tsProdutos = tsProdutos + txProdutos;

            }
            int iRetorno;
           iRetorno = DUAL.iImprimirTexto(tsProdutos + "<l></l>"
                    + "<l></l><b><ad>TOTAL CUPOM: " + tfTotalCupom.getText() + "</ad></b>"
                    + "<b><ad>VALOR PAGO: " + tfValorPago.getText() + "</ad></b>"
                    + "<b><ad>TROCO: " + tfTroco.getText() + "</ad></b>"
                    + "<sl>5</sl>"
                    + "<gui></gui><g></g>", 0);   
           
            if(iRetorno == 0){
                JOptionPane.showMessageDialog(null,
                    "Erro ao Imprimir o texto, verifique a impressora!\n" +
                    "Retorno [" + iRetorno + "]",
                    "Daruma DLL Framework",
                    JOptionPane.ERROR_MESSAGE);
            }
          
               Statement st2;
                try {
                    st2 = ConexaoPDVWindel.createStatement();
                    for (int i = 0; i<vetor_itens.size(); i++){
                        
                        ItemVenda itemVetor = new ItemVenda();
                        itemVetor = (ItemVenda) vetor_itens.elementAt(i);
                        
                        st2.execute("insert into VENDAS (DESCRICAO, BARRAS, QUANT, PRECO_UNIT,"
                                + "VALOR_TOTAL_ITEM, COD_CUPOM, DATA) values ("
                                + "\'" + itemVetor.getDescricao() + "\',"
                                + "\'" + itemVetor.getCodBarras() + "\',"
                                + "\'" + itemVetor.getQuantVetor() + "\',"
                                + "\'" + itemVetor.getPrecoUnit() + "\',"
                                + "\'" + itemVetor.getPrecoTotalItem() + "\',"
                                + "\'" + Cod_cupom + "\',"
                                + "\'" + (formatarDate.format(data)) + "\')");
                    }
                    vetor_itens.clear();
                } catch (SQLException e) {
                    JOptionPane.showMessageDialog(null, "Registros não inseridos!", "Erro", JOptionPane.INFORMATION_MESSAGE);
                }
            


        }
        if (evt.getKeyCode() == KeyEvent.VK_F9) {
            for (int i = 0; i<vetor_itens.size(); i++){
                ItemVenda itemVetor = new ItemVenda();
                itemVetor = (ItemVenda) vetor_itens.elementAt(i);
                System.out.println(itemVetor.getDescricao());
            }
            System.out.println("não deu"+vetor_itens.size());
        }
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            float tr = Float.valueOf(tfValorPago.getText().replace(",", "."));
            float troco = tr - Subtotal;
            tfTroco.setText(formatarFloat(troco));
        }
        if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
            this.dispose();
        }
        if (evt.getKeyCode() == KeyEvent.VK_F1) {
            rbDinheiro.setSelected(true);
            tfValorPago.setText("");
        }
        if (evt.getKeyCode() == KeyEvent.VK_F2) {
            rbCheque.setSelected(true);
            tfValorPago.setText(tfTotalCupom.getText());
        }
        if (evt.getKeyCode() == KeyEvent.VK_F3) {
            rbCrediario.setSelected(true);
            tfValorPago.setText(tfTotalCupom.getText());
        }
    }//GEN-LAST:event_tfValorPagoKeyPressed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JRadioButton rbCheque;
    private javax.swing.JRadioButton rbCrediario;
    private javax.swing.JRadioButton rbDinheiro;
    private javax.swing.JTextField tfTotalCupom;
    private javax.swing.JTextField tfTroco;
    private javax.swing.JTextField tfValorPago;
    // End of variables declaration//GEN-END:variables

    public String statusImpressora() {
        int iRetorno = DUAL.rStatusImpressora();
        switch (iRetorno) {
            case 0:
                return ("Impressora desligada");
            case 1:
                return ("Impressora OK");
            case -27:
                return ("Erro generico");
            case -50:
                return ("Impressora off line");
            case -51:
                return ("Impressora sem papel");
            case -52:
                return ("Impressora inicializando");
            default:
                return ("Retorno não esperado!");
        }
    }

    public boolean finalizarCupom() {
        cupomEncerrado = false;  //Marcamos que o dados 
        setModal(true);         //A dialog tem que ser modal. Só pode retornar do setVisible após ficar invisível.
        setVisible(true);       //Mostramos a dialog e esperamos o usuário escolher alguma coisa.
        return cupomEncerrado;   //Retornamos true, se ele pressionou ok.
    }

    public final String formatarFloat(float numero) {
        String retorno = "";
        DecimalFormat formatter = new DecimalFormat("0.00");
        try {
            retorno = formatter.format(numero);
        } catch (Exception ex) {
            System.err.println("Erro ao formatar numero: " + ex);
        }
        return retorno;
    }

    public String getFormatDec(String snumero) {
        snumero = snumero.replaceAll(",", ".");
        DecimalFormat df = new DecimalFormat("0.00");
        snumero = df.format(Double.parseDouble(snumero));
        snumero = snumero.replaceAll(",", ".");
        return snumero;
    }
}
